/*
 * Copyright (c) 2007 jNetX.
 * http://www.jnetx.com
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * jNetX. You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license
 * agreement you entered into with jNetX.
 *
 * $Id$
 */
package com.jnetx.javax.sip.header;

import com.jnetx.javax.sip.util.ByteArrayUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href="mailto:dparhonin@jnetx.ru">Dmitry Parhonin</a>
 * @version $Revision$
 */
public class AcceptEncodingHeaderParser extends ParametrizedHeaderParserBase<AcceptEncodingHeaderImpl> {
    private static final Log logger = LogFactory.getLog(AcceptEncodingHeaderParser.class);

    protected Log getLogger() {
        return logger;
    }

    public final AcceptEncodingHeaderImpl createLazily(byte[] data, int start, int end) {
        return new AcceptEncodingHeaderImpl(data, start, end);
    }

    public AcceptEncodingHeaderImpl[] parse(AcceptEncodingHeaderImpl header, byte[] data, int start, int end) throws ParseException {
        if (header == null) header = new AcceptEncodingHeaderImpl();
        int startOfData = start;
        List<AcceptEncodingHeaderImpl> headers = null;
        //Number of parts of the header value which can be translated into separate headers of the same type.
        while (startOfData < end) {
            startOfData = ByteArrayUtil.firstMissing(data, ' ', startOfData, end);
            if (startOfData == -1)
                fail("Cannot parse the header!", start);
            if (headers != null) {
                header = new AcceptEncodingHeaderImpl();
                headers.add(header);
            }
            int endOfPart = ByteArrayUtil.firstOccurence(data, ',', startOfData, end);
            if (endOfPart == -1)
                endOfPart = end;
            else if (headers == null) {
                headers = new ArrayList<AcceptEncodingHeaderImpl>();
                headers.add(header);
            }
            int startOfParameter = ByteArrayUtil.firstOccurence(data, ';', startOfData, endOfPart);
            final int endOfData = ByteArrayUtil.lastMissing(data, ' ', startOfData, startOfParameter != -1 ? startOfParameter : endOfPart);
            header.setEncoding(new String(data, startOfData, endOfData - startOfData + 1));
            if (startOfParameter != -1)
                parseParameters(header, data, startOfParameter, endOfPart);
            startOfData = endOfPart + 1;
        }
        if (headers != null)
            return headers.toArray(new AcceptEncodingHeaderImpl[headers.size()]);
        else
            return new AcceptEncodingHeaderImpl[]{header};
    }
}
/*
 * $Log$
 */